<!-- 领料单 -->
<template>
  <div class="edit-pack">
    <el-drawer :title="$i18n.t('mesMaterialRequisition.title')" :visible.sync="drawer" size="80%" :before-close="handleClose">
      <div class="padding-10">
        <!-- 查询表单 -->
        <ele-form-search :formConfig="searchConfig" @handleSearch="handleSearch" @handleReset="handleReset" ref="eleFormSearch"></ele-form-search>

        <div class="content">
          <el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-width="120px" :inline="true" class="form" :show-message="false">
            <el-table v-loading="tableLoading" class="table-pack" :data="ruleForm.mesRequisitionBillList || []" border :key="time" height="calc(100vh - 410px)">
              <el-table-column v-for="(ite, i) in column" :key="i" align="center" :prop="ite.prop" :label="ite.label" :fixed="ite.fixed || null" :width="ite.width || ''" show-overflow-tooltip>
              </el-table-column>
              <el-table-column :label="$i18n.t('mesMaterialRequisition.planQty')" align="center" width="160" fixed="right" :render-header="addRedStar">
                <template slot-scope="scope">
                  <el-form-item :prop="'mesRequisitionBillList.' + scope.$index + '.planQty'" :rules="rules.planQty">
                    <el-input-number controls-position="right" :min="0" :disabled="!(scope.row.updateFlag == 1)" v-model="scope.row.planQty" :precision="3"></el-input-number
                  ></el-form-item>
                </template>
              </el-table-column>

              <!-- 车间 -->
              <el-table-column :label="$i18n.t('mesMaterialRequisition.returnWorkshopCode')" width="160" align="center" fixed="right">
                <template slot-scope="scope">
                  <el-select
                    v-model="scope.row.returnWorkshopCode"
                    :placeholder="$i18n.t('mesMaterialRequisition.msg5')"
                    :disabled="!(scope.row.updateFlag == 1)"
                    @change="(val) => changeReturnWorkWorkshopCode(val, scope.row)"
                    filterable
                  >
                    <el-option v-for="item in workshopCodeList" :key="item.modelingCode" :label="item.modelingName" :value="item.modelingCode"> </el-option>
                  </el-select>
                </template>
              </el-table-column>
              <!-- 工位 -->
              <el-table-column :label="$i18n.t('mesMaterialRequisition.returnWorkCellCode')" width="160" align="center" fixed="right">
                <template slot-scope="scope">
                  <el-select
                    :disabled="!(scope.row.updateFlag == 1)"
                    v-model="scope.row.returnWorkCellCode"
                    :placeholder="$i18n.t('mesMaterialRequisition.msg4')"
                    @change="(val) => changeReturnWorkCellCode(val, scope.row)"
                    filterable
                  >
                    <el-option v-for="item in scope.row.workCellList" :key="item.modelingCode" :label="item.modelingName" :value="item.modelingCode"> </el-option>
                  </el-select>
                </template>
              </el-table-column>

              <!-- 时间 -->
              <el-table-column :label="$i18n.t('mesMaterialRequisition.latestGetDate')" width="200" align="center" fixed="right" :render-header="addRedStar">
                <template slot-scope="scope">
                  <el-form-item label="" :prop="'mesRequisitionBillList.' + scope.$index + '.planTime'" :rules="rules.planTime">
                    <el-date-picker
                      v-model="scope.row.planTime"
                      type="datetime"
                      :placeholder="$i18n.t('mesMaterialRequisition.msg6')"
                      :disabled="!(scope.row.updateFlag == 1)"
                      value-format="yyyy-MM-dd HH:mm:ss"
                      :pickerOptions="{
                        disabledDate: (time) => time.getTime() < new Date(new Date().setHours(0, 0, 0, 0))
                      }"
                    >
                    </el-date-picker>
                  </el-form-item>
                </template>
              </el-table-column>

              <el-table-column :label="$i18n.t('common.operation')" width="50" align="center" fixed="right">
                <template slot-scope="scope">
                  <el-button v-if="scope.row.updateFlag == 1" type="text" style="color: #3886e6;" @click="handleSave(scope.row)">{{ $i18n.t('common.save') }}</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-form>
        </div>
        <div class="flex-ac no-print">
          <div class="flex-ac">
            <el-button @click="handleClose">{{ $i18n.t('common.cancel') }}</el-button>
            <!-- <el-button type="primary" @click="handleSubmit">下发领料</el-button> -->
          </div>
        </div>
      </div></el-drawer
    >
  </div>
</template>

<script>
// import { uniqueKey } from "@/utils/judge.js";
import { getDict } from '@/api/common.js'
import eleFormSearch from '@/components/ele-form-search/index'
//例如：import 《组件名称》 from '《组件路径》';
import { getPickMaterials, getWareStock, getWareList, saveMaterialList, getLineCodeListNew as getReturnWorkshopCodeList } from '@/api/order/mesProdOrder.js'
import {
  getLineCodeList //查询线体
} from '@/api/employee/mesUserExtend'
//   getReturnWorkshopCodeList,

import { getMaterialListById, getMaterialListByIdDialog as mesRequisitionOrderMaterials, updateMaterial } from '@/api/materialRequisition/mesMaterialRequisition'

import { getMaterialListByIdInfo } from '@/api/materialRequisition/mesRequisitionOrderMaterials'
export default {
  name: 'pickingList',
  //import引入的组件需要注入到对象中才能使用
  components: { eleFormSearch },
  props: {
    type: 0
  },
  data() {
    //这里存放数据
    const self = this
    return {
      drawer: false,
      loading: false,
      tableLoading: false,
      time: 0,
      submitVisible: false, //超领弹窗
      numberValidateForm: {
        overCollectionReason: '',
        overPickReason: ''
      }, //超领的表单
      overReasonList: [], //超领原因option
      excessTableData: [], //超额table
      topList: [],
      workshopList: [], //仓库列表
      workshopCodeList: [], //车间列表
      searchConfig: {
        inline: true,
        formDesc: {
          orderNo: {
            type: 'input',
            label: $i18n.t('mesRequisitionOrderMaterialsEditlog.orderNo') // 单据编号
          },
          materialName: {
            type: 'input',
            label: $i18n.t('mesRequisitionOrderMaterialsEditlog.materialName') // 物料名称
          },
          returnWorkshopCode: {
            type: 'select',
            label: $i18n.t('mesRequisitionOrderMaterialsEditlog.returnWorkshopName'), // 配送车间名称
            prop: {
              value: 'modelingCode',
              text: 'modelingName'
            },
            options: async (data) => {
              const params = {
                modelingCode: self.$store.getters.factoryCode,
                level: 4,
                modelingType: '0'
              }
              const list = await getReturnWorkshopCodeList(params)
              return list.data.result
            }
          },
          returnWorkCellCode: {
            type: 'select',
            label: $i18n.t('mesRequisitionOrderMaterialsEditlog.returnWorkCellName'), // 配送工位名称
            prop: {
              value: 'modelingCode',
              text: 'modelingName'
            },
            optionsLinkageFields: ['returnWorkshopCode'],
            options: async (data) => {
              if (!data.returnWorkshopCode) return []
              let res = await getReturnWorkshopCodeList({
                modelingCode: data.returnWorkshopCode,
                level: 6
              })
              return res.data.result
            }
          },
          planCode: {
            type: 'input',
            label: $i18n.t('mesRequisitionOrderMaterialsEditlog.planCode') // 生产订单编码
          },
          // materialName: {
          //   type: 'input',
          //   label: $i18n.t('mesRequisitionOrderMaterialsEditlog.prodName') // "产品名称",
          // },

          //   status: {
          //     type: "select",
          //     label: $i18n.t("mesRequisitionOrderMaterialsEditlog.status"), // 领料状态:0创建1领料中2已完成3已关闭
          //     prop: {
          //       value: "value",
          //       text: "description",
          //     },
          //     options: async (data) => {
          //       const list = await getStatusList();
          //       return list.data.result;
          //     },
          //   },

          warehouseCode: {
            label: $i18n.t('mesWaitPickOrderMaterials.warehouseCode'),
            type: 'select',
            prop: {
              value: 'modelingCode',
              text: 'modelingName'
            },
            options: async (data) => {
              const params = {
                modelingCode: self.$store.getters.factoryCode,
                level: 4,
                modelingType: '1'
              }
              const list = await getLineCodeList(params)
              return list.data.result
            }
          },
          latestGetDate: {
            type: 'datetimerange',
            label: $i18n.t('mesWaitPickOrderMaterials.latestGetDate'), // "计划时间",
            attrs: {
              valueFormat: 'yyyy-MM-dd HH:mm:ss',
              searchArrKey: ['planTimeMin', 'planTimeMax']
            }
          }
        }
      },
      ruleForm: {
        tableData: [],
        prod: '', //上方筛选条件
        warehouseCode: '', //选择仓库
        idList: []
      },
      countObj: {}, //数量统计
      rules: {
        planQty: [
          {
            required: true,
            message: $i18n.t('mesMaterialRequisition.msg2'),
            trigger: 'blur'
          }
        ],
        planTime: [
          {
            required: true,
            message: $i18n.t('mesMaterialRequisition.msg3'),
            trigger: 'blur'
          }
        ]
      },
      column: [
        {
          label: $i18n.t('mesMaterialRequisition.orderNo'), // "单据编码",
          prop: 'orderNo',
          width: 180
        },
        {
          label: $i18n.t('mesMaterialRequisition.materialCode'), // "物料编码",
          prop: 'materialCode',
          width: 180
        },
        {
          label: $i18n.t('mesMaterialRequisition.materialName'), //"物料名称",
          prop: 'materialName',
          width: 180
        },
        {
          label: $i18n.t('mesMaterialRequisition.unit'), //"单位",
          prop: 'unit',
          width: 80
        },
        {
          label: $i18n.t('mesMaterialRequisition.warehouseName'), //"仓库",
          prop: 'warehouseName',
          width: 140
        },
        {
          label: $i18n.t('mesMaterialRequisition.planCode'), // "订单编码",
          prop: 'planCode',
          width: 180
        },
        {
          label: $i18n.t('mesMaterialRequisition.prodCode'), //"产品编码",
          prop: 'prodCode',
          width: 120
        },
        {
          label: $i18n.t('mesMaterialRequisition.prodName'), // "产品名称",
          prop: 'prodName',
          width: 120
        }
      ]
    }
  },
  //监控data中的数据变化
  watch: {},
  //方法集合
  methods: {
    async init(data) {
      try {
        this.loading = true
        if (this.type) {
          this.ruleForm.idList = data.map((ite) => ite.id)

          this.handleSearch(() => {
            this.$nextTick(() => {
              this.$refs.eleFormSearch.formData = {}
            })
          })
        } else {
          let res = await getMaterialListById(data.map((ite) => ite.id).join(','))
          let { result } = res.data
          this.ruleForm.idList = result.map((ite) => ite.id)
          this.drawer = true
          this.ruleForm.mesRequisitionBillList = result
          this.$nextTick(() => {
            this.$refs.eleFormSearch.formData = {}
            this.ruleForm.mesRequisitionBillList.map((ite) => {
              this.getWorkCellList(ite)
            })
          })
        }
      } finally {
        this.loading = false
      }
    },

    // 保存
    handleSave(row) {
      this.$refs.ruleForm.validate(async (valid) => {
        if (valid) {
          let { id, planQty, returnWorkshopCode, returnWorkCellCode, returnWorkshopName, returnWorkCellName, planTime } = row
          let res = await updateMaterial({
            id,
            planQty,
            returnWorkshopCode,
            returnWorkCellCode,
            returnWorkshopName,
            returnWorkCellName,
            planTime
          })
          this.$message.success($i18n.t('common.editSuccess'))
          this.handleSearch()
        } else {
          this.$message.error("$i18n.t('mesMaterialRequisition.msg7')")
          return false
        }
      })
    },
    async handleSearch(callback) {
      try {
        this.tableLoading = true
        let obj = this.$refs.eleFormSearch ? this.$refs.eleFormSearch.formData : {}
        //console.log(9, this.$refs);
        if (obj.latestGetDate) {
          let [planTimeMin, planTimeMax] = obj.latestGetDate
          obj.planTimeMin = planTimeMin
          obj.planTimeMax = planTimeMax
        } else {
          obj['planTimeMin'] = null
          obj['planTimeMax'] = null
        }
        let api = this.type ? getMaterialListByIdInfo : mesRequisitionOrderMaterials
        let res = await api({
          idList: this.ruleForm.idList,
          ...obj
        })
        let { result } = res.data
        this.drawer = true
        this.$set(this.ruleForm, 'mesRequisitionBillList', result)

        this.ruleForm.mesRequisitionBillList.map((ite) => {
          this.getWorkCellList(ite)
        })
        this.time = Date.now()
        //  console.log(888,callback)
        callback ? callback() : null
      } catch (err) {
        console.error(err)
        this.drawer = false
      } finally {
        this.tableLoading = false
      }
    },
    handleReset() {
      this.handleSearch()
    },
    //移除一行容量数据
    handleDelRow(idx) {
      this.$nextTick(() => {
        this.ruleForm.mesRequisitionBillList.splice(idx, 1)
      })
    },

    // 上方点击切换
    handerItem(data) {
      ;(this.topList || []).map((ite) => {
        ite.map((item) => {
          this.$set(item, 'active', false)
        })
      })
      this.$set(data, 'active', true)
      this.tableLoading = true
      setTimeout(() => {
        this.tableLoading = false
      }, 500)
      this.ruleForm = data
    },
    // 封装提交领料单数据
    setSubmitData() {
      let data = []
      this.topList.map((ite) => {
        ;(ite || []).map((item) => {
          item.mesRequisitionBillList.map((a) => {
            ;(a.prodCode = item.prodCode), (a.prodName = item.prodName)
          }),
            data.push({
              planCode: item.planCode,
              ...this.numberValidateForm,
              mesRequisitionBillList: item.mesRequisitionBillList || []
            })
        })
      })
      return data
    },

    // tablet表头必填加*
    addRedStar(h, { column }) {
      return [h('span', { style: 'color: red' }, '*'), h('span', ' ' + column.label)]
    },

    //获得线体数据
    getWorkCellList(data) {
      if (data.returnWorkshopCode) {
        getReturnWorkshopCodeList({
          modelingCode: data.returnWorkshopCode,
          level: 6
        }).then((res) => {
          this.$set(data, 'workCellList', res.data.result)
        })
      }
    },
    //选择车间
    changeReturnWorkWorkshopCode(val, row) {
      this.$nextTick(() => {
        //获得线体数据
        getReturnWorkshopCodeList({
          modelingCode: val,
          level: 6
        }).then((res) => {
          this.$set(row, 'workCellList', res.data.result)
        })
        let obj = this.workshopCodeList.find((ite) => ite.modelingCode == val)
        this.$set(row, 'returnWorkshopName', obj.modelingName)

        //console.log(88, row);
      })
    },
    changeReturnWorkCellCode(val, row) {
      this.$nextTick(() => {
        let obj = row.workCellList.find((ite) => ite.modelingCode == val)

        this.$set(row, 'returnWorkCellName', obj.modelingName)

        //console.log(888, this.topList);
      })
    },
    // 根据仓库物料查询, 库存
    async workshopSelect(val, row, type) {
      try {
        // 下方有值才调用
        let { mesRequisitionBillList } = this.ruleForm
        if (mesRequisitionBillList && mesRequisitionBillList.length) {
          let res = await getWareStock({
            warehouseCode: val,
            goodsCodeList: type ? [row.materialCode] : (mesRequisitionBillList || []).map((val) => val.materialCode)
          })
          let { result } = res.data
          if (type) {
            this.$set(row, 'inventory', result[0]?.amount ?? 0)
            let obj = this.workshopList.find((ite) => ite.modelingCode == val)
            this.$set(row, 'warehouseName', obj.modelingName)
            this.$set(row, 'warehouseCode', obj.modelingCode)
          } else {
            result.map((ite, i) => {
              this.$set(this.ruleForm.mesRequisitionBillList[i], 'inventory', ite.amount)
              let obj = this.workshopList.find((ite) => ite.modelingCode == val)

              // 设置仓库名称
              this.$set(this.ruleForm.mesRequisitionBillList[i], 'warehouseName', obj.modelingName)
              this.$set(this.ruleForm.mesRequisitionBillList[i], 'warehouseCode', val)
            })
          }
        }
      } catch (error) {
        //console.error("错误信息", error);
      }
    },
    //获取当前物料
    async getWorkshopList() {
      let res = await getWareList(this.$store.getters.factoryCode)
      this.workshopList = res.data.result
    },
    //获取当前物料
    async initWorkshopCodeList() {
      const params = {
        modelingCode: this.$store.getters.factoryCode,
        level: 4,
        modelingType: '0'
      }
      let res = await getReturnWorkshopCodeList(params)
      this.workshopCodeList = res.data.result
    },
    handleClose() {
      this.$refs.eleFormSearch.formData = {}
      this.drawer = false
    },
    // 返回上一页,并且关闭当前页签
    goback() {
      const { name, path } = this.$route
      this.$store.commit('SET_DELETE', name)
      this.$store.commit('SET_DELTOPMENUS', { name, path })
      this.$router.back()
    }
  },
  //生命周期 - 创建完成（可以访问当前this实例）
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {
    this.getWorkshopList()
    this.initWorkshopCodeList()
  }
}
</script>
<style scoped lang="scss">
.edit-pack {
  width: 100%;
  height: 100%;
  .top {
    width: 100%;

    .active {
      background: #dbeaff !important;
      .card {
        background-color: #4279e1 !important;
        border: 1px solid #1073ea !important;
        .pack {
          color: white !important;
          .small {
            color: #ccc6c6 !important;
          }
        }
        .number {
          background: #ffffff6b;
        }
      }
    }
    .card {
      height: 110px;
      cursor: pointer;
      position: relative;
      .number {
        position: absolute;
        right: 0px;
        bottom: 0px;
        width: 20px;
        // background: #e5e5e5;
        height: 20px;
        display: flex;
        justify-content: center;
        border-radius: 10px 0px 0px 0px;
        align-items: center;
      }
      /deep/.el-card__body {
        height: 100% !important;
      }
      .pack {
        color: #333;
        display: flex;
        flex-direction: column;
        height: 100%;
        justify-content: space-between;

        .p1 {
          font-size: 14px;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;

          .small {
            color: rgb(153, 153, 153);
          }
        }
      }
    }
  }
  .content {
    margin-top: 18px;
    // border: 1px solid #e5e5e5;
    border-bottom: 0px;
    padding-left: 10px;
    padding-right: 10px;
    .top-btn {
      margin-top: 18px;
    }
    .form {
      width: 100%;
      height: 100%;
    }
    .table-pack {
      /deep/.el-form-item {
        margin: 0;
      }
    }
  }

  .over-pick {
    /deep/.el-dialog__header {
      text-align: center;
      background: #ecc717;
    }
  }
  .no-print {
    background: #ffffff;
    padding: 16px 24px;
    // border: 1px solid #e5e5e5;
    // border-top: 1px solid #e5e5e5;

    display: flex;
    span {
      color: #ff4656;
    }
    .chunk_flag {
      width: 10px;
      height: 10px;
      background: #f4bb5b;
      border-radius: 2px;
      margin-right: 8px;
    }
  }
  .flex {
    display: flex;
  }

  .flex-j-sb {
    display: flex;
    justify-content: space-between;
  }
  .flex-ac {
    display: flex;
    align-items: center;
  }

  .padding-10 {
    padding: 10px;
  }
  .m-r-10 {
    margin-right: 10px;
  }
}
</style>
